from PyQt5.QtWidgets import (
    QMainWindow, QTabWidget, QPushButton, QLineEdit, QVBoxLayout, QHBoxLayout, QWidget, QMessageBox, QFileDialog, QTableWidgetItem
)
from PyQt5.QtGui import QFont
from PyQt5.QtCore import Qt
from ui.emt_tab import EMTTab
from ui.comp_list_tab import CompListTab
import json
import os

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        try:
            with open("file_path.txt", "r") as f:
                self.last_file_path = f.readlines()[0].strip()
                self.last_folder_path = os.path.dirname(self.last_file_path)
        except:
            try:
                with open("folder_path.txt", "r") as f:
                    self.last_folder_path = f.readlines()[0].strip()
            except:
                self.last_folder_path = None
            self.last_file_path = None
        self.initUI()
        if self.last_file_path:
            self.load_json(False)

    def initUI(self):
        self.setWindowTitle("JSON Generator")
        self.setGeometry(100, 100, 800, 600)

        # 创建主布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        self.layout = QVBoxLayout(central_widget)

        # 创建地址栏和按钮的水平布局
        file_path_layout = QHBoxLayout()

        # 添加地址输入框
        self.file_path_input = QLineEdit()
        self.file_path_input.setPlaceholderText("Enter file path to save JSON")
        self.file_path_input.setText(self.get_default_file_path())  # 设置默认文件路径
        file_path_layout.addWidget(self.file_path_input)

        # 添加 Load 按钮
        self.load_button = QPushButton("Load")
        self.load_button.clicked.connect(lambda:self.load_json(True))
        file_path_layout.addWidget(self.load_button)

        # # 添加 Browse 按钮
        # self.browse_button = QPushButton("Browse")
        # self.browse_button.clicked.connect(self.select_folder)
        # file_path_layout.addWidget(self.browse_button)

        # 将水平布局添加到主布局
        self.layout.addLayout(file_path_layout)

        # 创建 Tab 控件
        self.tabs = QTabWidget()
        self.layout.addWidget(self.tabs)

        # EMT 标签页
        self.emt_tab = EMTTab()
        self.tabs.addTab(self.emt_tab, "EMT")

        # Comp List 标签页
        self.comp_list_tab = CompListTab()
        self.tabs.addTab(self.comp_list_tab, "Comp List")

        # 生成 JSON 按钮
        self.generate_button = QPushButton("Generate JSON")
        self.generate_button.clicked.connect(self.generate_json)
        self.layout.addWidget(self.generate_button)

    def get_default_file_path(self):
        # 如果有上次记录的文件夹路径，则使用上次的路径
        if self.last_file_path:
            return self.last_file_path
        elif self.last_folder_path:
            return os.path.join(self.last_folder_path, "new.json")
        # 否则使用程序运行目录
        else:
            return os.path.join(os.getcwd(), "new.json")

    def generate_json(self):
        emt_params = self.emt_tab.get_params()
        comp_list = self.comp_list_tab.get_components()

        json_data = {
            "EMT": {
                "Params": emt_params
            },
            "comp_list": comp_list
        }

        json_str = json.dumps(json_data, indent=4)

        # 获取用户输入的文件路径
        file_path = self.file_path_input.text()
        if not file_path:
            QMessageBox.warning(
                self, "Warning", "Please enter a valid file path.")
            return

        try:
            # 确保文件夹存在
            folder_path = os.path.dirname(file_path)
            if not os.path.exists(folder_path):
                os.makedirs(folder_path)

            # 将 JSON 数据写入文件
            with open(file_path, "w") as file:
                file.write(json_str)
            QMessageBox.information(
                self, "Success", f"JSON file saved successfully at {file_path}")
        except Exception as e:
            QMessageBox.critical(
                self, "Error", f"Failed to save JSON file: {e}")

    def load_json(self, need_dialog = True):
        if need_dialog: 
            file_path, _ = QFileDialog.getOpenFileName(
                self, "Open JSON File", self.last_folder_path, "JSON Files (*.json)")
            if file_path:
                with open("file_path.txt", "w") as f:
                    f.write(file_path)
                self.last_file_path = file_path
            if not file_path:
                return
            with open("folder_path.txt", "w") as f:  # 打开文件用于写入
                f.write(os.path.dirname(file_path))
            # 保存上次选择的文件夹路径
            self.last_folder_path = os.path.dirname(file_path)

        try:
            if not need_dialog:
                file_path = self.last_file_path
            # 读取 JSON 文件
            with open(file_path, "r") as file:
                json_data = json.load(file)

            # 清空当前表格内容
            self.emt_tab.table.setRowCount(0)
            self.comp_list_tab.table.setRowCount(0)

            # 填充 EMT 参数
            emt_params = json_data.get("EMT", {}).get("Params", [])
            for param in emt_params:
                self.emt_tab.add_param()
                row = self.emt_tab.table.rowCount() - 1
                self.emt_tab.table.setItem(
                    row, 0, QTableWidgetItem(param.get("name", "")))
                self.emt_tab.table.cellWidget(
                    row, 1).setCurrentText(param.get("type", ""))
                self.emt_tab.table.setItem(
                    row, 2, QTableWidgetItem(param.get("value", "")))
                self.emt_tab.table.setItem(
                    row, 3, QTableWidgetItem(param.get("Description", "")))
                self.emt_tab.table.setItem(
                    row, 4, QTableWidgetItem(param.get("unit", "")))

            # 填充 Comp List
            comp_list = json_data.get("comp_list", [])
            for component in comp_list:
                self.comp_list_tab.add_component()
                row = self.comp_list_tab.table.rowCount() - 1
                self.comp_list_tab.table.setItem(
                    row, 0, QTableWidgetItem(component.get("name", "")))
                self.comp_list_tab.table.setItem(
                    row, 1, QTableWidgetItem(component.get("class_name", "")))
                self.comp_list_tab.table.setItem(
                    row, 2, QTableWidgetItem(", ".join(component.get("nodes", []))))
                self.comp_list_tab.set_component_params(
                    row, component.get("Params", []))
                self.comp_list_tab.set_component_sub_comps(
                    row, component.get("sub_comps", []))
            # if need_dialog:
            #     QMessageBox.information(
            #     self, "Success", f"JSON file loaded successfully from {file_path}")
        except Exception as e:
            QMessageBox.critical(
                self, "Error", f"Failed to load JSON file: {e}")
